import os,re,sys,shutil
from xml.dom import minidom
p0=sys.argv[1]+r'\res'
a=p0+r'\values'


fl=['']+[i[6:] for i in os.listdir(p0) if re.search('^values-[a-z]{2}(?:-r[A-Z]{2})?$',i)]
for i in ['-zh','-zh-rCN']:
	if i in fl:	
		fl.remove(i)
		fl=[i]+fl
		
if len(fl)<=1:exit()

mpg=lambda p:minidom.parse(p).getElementsByTagName('public')
mpdc=lambda p:minidom.parse(p).documentElement.childNodes
cc=lambda c:[i for i in ['string','array','plurals','dimen','id','color'] if c.startswith(i)][0]

for c in os.listdir(a+(fl[0] or fl[1])):
	doc=minidom.Document()
	root=doc.createElement('resources')
	l=[i.getAttribute('name') for i in mpg(a+r'\public.xml') if i.getAttribute('type')==cc(c)] 	
	for ii in fl:
		for i in mpdc(a+ii+'\\'+c):
			if i.nodeType==i.ELEMENT_NODE:
				e=i.getAttribute('name')
				if e in l:
					root.appendChild(i)
					l.remove(e)
		if not l:break
	doc.appendChild(root)
	f=l and '1' or ''
	f=open(a+'\\'+f+c,'w')
	f.write(doc.toprettyxml(encoding='utf-8'))
	f.close()
	print c,l

for i in fl:
	if i:#shutil.move(a+i,p0[:-3]+'0\\values'+i)
		shutil.rmtree(a+i)